#include <stdio.h>
#include <string.h>

/* START:: code for queue */
#define QUEUE_SIZE 32
int out_queue_err = 0;

typedef struct {
	int data[QUEUE_SIZE];
	int inpos;
	int outpos;
} queue_t;

void init_queue(queue_t *q)
{
	memset(q->data, 0, sizeof(int) * QUEUE_SIZE);
	q->inpos = q->outpos = 0;
}

int in_queue(queue_t *q, int new)
{
	int pos = (q->inpos + 1) % QUEUE_SIZE; 
	if (pos == q->outpos)
		return -1;
	q->data[q->inpos] = new;
	q->inpos = pos;
	return 0;
}

int out_queue(queue_t *q) 
{
	int ret;

	if (q->outpos == q->inpos) {
		out_queue_err = -1;
		return -1;
	}

	ret = q->data[q->outpos];
	q->outpos = (q->outpos + 1) % QUEUE_SIZE;

	return ret;
}

int empty(queue_t *q)
{
	return q->inpos == q->outpos;
}
/* END:: code for queue */

/* START:: code for stack */
typedef struct stack {
	queue_t q[2];
	int in;
} stack_t;

void init_stack(stack_t *s)
{
	init_queue(s->q);
	init_queue(s->q + 1);
	s->in = 0;
}

int push(stack_t *s, int data)
{
	return in_queue(s->q + s->in, data);
}

int pop(stack_t *s) 
{
	int ret, other;

	if (s->in == 0)
		other = 1;
	else 
		other = 0;

	ret = out_queue(s->q + s->in);
	while (!empty(s->q + s->in)) {
		in_queue(s->q + other, ret);
		ret = out_queue(s->q + s->in);
	}
	s->in = other;

	return ret;
}

/* END:: code for stack */

int main()
{
	stack_t s[1];
	int i, data;

	init_stack(s);
	for (i = 0; i < 8; i++)
		push(s, i);
	for (i = 0; i < 8; i++) {
		data = pop(s);
		printf("%d\n", data);
	}
	
	return 0;
}


